home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 10818 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.4 KB  |  51 lines

  1. Path: isonews.bbn.hp.com!hpbblb!news
  2. From: Matthias Dittrich <matti>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Output to file vs. cout
  5. Date: 11 Mar 1996 13:09:36 GMT
  6. Organization: Hewlett-Packard Co.
  7. Message-ID: <4i18mg$ba5@hpbblb.bbn.hp.com>
  8. References: <JL.96Mar7165152@thyme.id.dth.dk>
  9. NNTP-Posting-Host: trabant.bbn.hp.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=iso-8859-1
  12. Content-Transfer-Encoding: 8bit
  13. X-Mailer: Mozilla 1.1N (X11; I; HP-UX A.09.07 9000/712)
  14. X-URL: news:JL.96Mar7165152@thyme.id.dth.dk
  15.  
  16. jl@id.dth.dk (J°rn Lind-Nielsen) wrote:
  17. >
  18. >Here's another of the probs that comes from porting C to C++:
  19. >
  20. >- I want to be able to redirect program output to either a file or cout.
  21. >  Typically this would be selected by a commandline option ("-o outfile").
  22. >
  23. >- In C I would do something like this:
  24. >
  25. >
  26. >     main()
  27. >     {
  28. >       FILE *outputfile;
  29. >
  30. >       if (commandline == do_output_to_file)
  31. >          outputfile = stdout;
  32. >       else
  33. >          outputfile = fopen(passed_filename, "w");
  34. >
  35. >       fprintf(outfile, "Hello world\n");
  36. >
  37. >       fclose(outfile);  /* Maybe - not allways necassary */
  38. >     }
  39. >
  40. >- The question is:  How is this done in C++ ?
  41. >
  42. >.......
  43. ofstream outfile(passed_filename); /* this constructor opens your file */
  44. outfile << "Hello world" << endl;  /* writes the string */
  45.  
  46. The destructor closes the file and of course you should do some error checking.
  47.  
  48. Good luck,
  49. Matthias
  50.  
  51.